// +build windows
package notifyicon

import (
	"errors"
	"os"
	"path/filepath"
	"time"

	"github.com/lxn/walk"
)

var notifyIcon *walk.NotifyIcon
var icon *walk.Icon
var flickerIcon bool //是否闪烁

//显示气泡通知
func ShowCustom(title, custom string) (err error) {
	if notifyIcon == nil {
		err = errors.New("Notify icon is null.")
		return
	}
	return notifyIcon.ShowCustom(title, custom)
}

//设置鼠标停留提示信息
func SetTip(title string) (err error) {
	if notifyIcon == nil {
		err = errors.New("Notify icon is null.")
		return
	}
	return notifyIcon.SetToolTip(title)
}

//是否闪烁
func SetFlickerIcon(b bool) {
	flickerIcon = b
}

//图标开始闪烁
func FlickerIcon() {
	for {
		if flickerIcon {
			notifyIcon.SetIcon(nil)
			time.Sleep(time.Millisecond * 500)
			notifyIcon.SetIcon(icon)
			time.Sleep(time.Millisecond * 500)
		} else {
			time.Sleep(time.Second)
		}
	}
}

//运行ui
//必须在main函数的最后一行运行
func Run(title string, iconID int) (err error) {
	mainWindow, err := walk.NewMainWindow()
	if err != nil {
		return
	}

	//从文件中加载图标
	//icon, err = walk.NewIconFromFile("app.ico")
	icon, err = walk.NewIconFromResourceId(iconID)
	if err != nil {
		return
	}

	//创建一个托盘
	notifyIcon, err = walk.NewNotifyIcon()
	if err != nil {
		return
	}
	defer notifyIcon.Dispose()

	// 设置托盘图标.
	if err = notifyIcon.SetIcon(icon); err != nil {
		return
	}

	//设置托盘提示文字
	if title == "" {
		title = os.Args[0]
		title = filepath.Base(title)
	}
	if err = notifyIcon.SetToolTip(title); err != nil {
		return
	}

	// When the left mouse button is pressed, bring up our balloon.
	notifyIcon.MouseDown().Attach(func(x, y int, button walk.MouseButton) {
		if button != walk.LeftButton {
			return
		}
		//左键按下取消闪烁
		SetFlickerIcon(false)
	})

	//创建一个退出菜单
	exitAction := walk.NewAction()
	if err = exitAction.SetText("E&xit"); err != nil {
		return
	}
	//实现退出菜单的功能
	exitAction.Triggered().Attach(func() {
		if ExitMsgFunc != nil {
			ExitMsgFunc("Admin exit this app.")
		}
		walk.App().Exit(0)
	})

	//把退出菜单添加到到托盘的快捷菜单
	if err = notifyIcon.ContextMenu().Actions().Add(exitAction); err != nil {
		return
	}

	//设置托盘图标可见
	if err = notifyIcon.SetVisible(true); err != nil {
		return
	}

	//运行消息循环
	mainWindow.SetVisible(false)
	mainWindow.Run()
	return
}
